<?php
/**
 * Created by PhpStorm.
 * User: jolly
 * Date: 14-6-4
 * Time: 下午1:26
 */

class StudentAuth
{

    public static  $cookie_jar=null;
    /**
     * @param $url
     * @param bool $postdata  post的数据
     * @param bool $referer
     * @param bool $autoconvert  是否自动转编码
     * @return array
     */
    public static function getHtmlCurl($url,$postdata=false,$referer=false,$autoconvert=true){
        //global $cookie_jar;
        /** @var $CI CI */
        if( ! self::$cookie_jar){
            self::$cookie_jar = tmpfile();
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_COOKIEJAR, self::$cookie_jar);
        curl_setopt($ch, CURLOPT_COOKIEFILE, self::$cookie_jar);

        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1 ); // 使用自动跳转
        if ($referer) {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }else{
            curl_setopt($ch, CURLOPT_AUTOREFERER, 1 ); // 自动设置Referer
        }


        if ($postdata) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        }

        $content=curl_exec($ch);


        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);//头长度
        $header = substr($content, 0, $headerSize);
        $body = substr($content, $headerSize);

        if($autoconvert){//自动转换编码
            $fileType = mb_detect_encoding($body , array('UTF-8','GBK','LATIN1','BIG5')) ;
            if( $fileType != 'UTF-8'){
                $body= mb_convert_encoding($body ,'utf-8' , $fileType);
            }
        }

        $result=array('url'=>$url,'error'=>curl_error($ch),'header'=>$header,'body'=>$body);
        curl_close($ch);
        return $result;
    }
}